import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react'
import { Form, Row, Col, Button, message } from 'antd'
import PropTypes from 'prop-types'
import moment from 'moment'
import { UpOutlined, DownOutlined } from '@ant-design/icons'
import { awaitWrap } from '@js/tool'
import style from './Index.module.less'
import paramList from './paramList'
import { getDictinarys, getCaseTypeTree } from './ajax/index'

const { Item } = Form
const layout = {
  labelCol: { flex: '116px' }
}

// 切换按钮
function ToggleBtn ({ value, onChange }) {
  return (
    <Button type='link' onClick={() => { onChange(!value) }}>
      <span>{value ? '收起' : '展开'}</span>
      {value ? <UpOutlined /> : <DownOutlined />}
    </Button>
  )
}

// 初始化字典
async function initDictionary (setDictionary) {
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getDictinarys())
  hide()
  if (e) {
    return message.warning(e.message)
  }
  setDictionary(d)
}

// 初始化案件类型树
async function initCaseTypeList (setCaseTypeList) {
  const [e, d] = await awaitWrap(getCaseTypeTree())
  if (e) {
    return message.warning(e.message)
  }
  let s = []
  d.forEach(li => {
    if (li.title === '金融案件') {
      s = li.children.map(o => o.value)
    }
  })
  setCaseTypeList(s)
}

// 根据表单数据生成condition
function getCondition (form, extendCondition, fn) {
  if (form.beginTime && form.endTime && form.endTime < form.beginTime) {
    return message.warning('收案结束日期不能早于收案开始日期')
  }
  if (form.closureBeginTime && form.closureEndTime && form.closureEndTime < form.closureBeginTime) {
    return message.warning('结案结束日期不能早于结案开始日期')
  }
  const condition = []
  const type = form.type
  if (form.year) {
    condition.push({ k: 'accept_year', o: '=', v: form.year })
  }
  if (form.beginTime) {
    condition.push({ k: type, o: '>=', v: Math.floor(moment(form.beginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
  }
  if (form.endTime) {
    condition.push({ k: type, o: '<=', v: Math.floor(moment(form.endTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
  }
  if (form.caseno) {
    condition.push({ k: 'caseno_desc|counter_caseno_desc', o: 'like', v: `%${form.caseno}%` })
  }
  if (form.counter_caseno_desc) {
    condition.push({ k: 'counter_caseno_desc', o: 'like', v: `%${form.counter_caseno_desc}%` })
  }
  if (form.applicant) {
    condition.push({ k: 'applicant_name', o: 'like', v: `%${form.applicant}%` })
  }
  if (form.respondent) {
    condition.push({ k: 'respondent_name', o: 'like', v: `%${form.respondent}%` })
  }
  if (form.cause_action && form.cause_action.length) {
    const o = form.cause_use_type === '包含' ? 'in' : 'not in'
    condition.push({ k: 'cause_action', o, v: form.cause_action.join() })
  }
  if (form.procedure && form.procedure.length) {
    condition.push({ k: 'procedure', o: 'in', v: form.procedure.join() })
  }
  if (form.closure_type && form.closure_type.length) {
    condition.push({ k: 'closure_type', o: 'in', v: form.closure_type.join() })
  }
  if (form.party_area_tag && form.party_area_tag.length) {
    condition.push({ k: 'party_area_tag', o: 'in', v: form.party_area_tag.join() })
  }
  if (form.minDisputeAmount) {
    condition.push({ k: 'dispute_amount', o: '>=', v: form.minDisputeAmount * 10000 })
  }
  if (form.maxDisputeAmount) {
    condition.push({ k: 'dispute_amount', o: '<=', v: form.maxDisputeAmount * 10000 })
  }
  if (form.processerid) {
    condition.push({ k: 'processerid', o: '=', v: form.processerid })
  }
  if (form.arbitratorid) {
    condition.push({ k: 'arbitratorids', o: 'like', v: `%${form.arbitratorid}%` })
  }
  if (form.accept_structure) {
    condition.push({ k: 'accept_structure', o: '=', v: form.accept_structure })
  }
  if (form.serieno) {
    condition.push({ k: 'serieno', o: 'like', v: `%${form.serieno}%` })
  }
  if (form.casetype && form.casetype !== '全部') {
    condition.push({ k: 'casetype', o: form.casetype !== '金融案件' ? '<>' : '=', v: '金融案件' })
  }
  if (form.casesubtype && form.casesubtype.length) {
    condition.push({ k: 'casesubtype', o: 'in', v: form.casesubtype })
  }
  if (form.causeactionType && form.causeactionType.length) {
    condition.push({ k: 'causeactionType', o: '=', v: form.causeactionType.join() })
  }
  if (form.party_address) {
    condition.push({ k: 'party_address', o: 'like', v: `%${form.party_address}%` })
  }
  if (form.accept_report_type) {
    condition.push({ k: 'accept_report_type', o: 'like', v: `%${form.accept_report_type}%` })
  }
  if (form.submittalid === '是') {
    condition.push({ k: 'submittalid', o: 'not null' })
  } else if (form.submittalid === '否') {
    condition.push({ k: 'submittalid', o: 'null' })
  }
  const r = extendCondition(condition, form)
  fn(r.condition, r.formData)
}

// 重置函数
function resetHandle (ref) {
  const c = ref.current
  c.resetFields()
  setTimeout(() => {
    c.submit()
  }, 0)
}

function Main ({ disableParams, params, name, onChange, initialValues, extendParams, extendCondition }, ref) {
  const formRef = useRef(null)
  const [visible, setVisible] = useState(false)
  const [caseTypeList, setCaseTypeList] = useState([])
  const [dictionary, setDictionary] = useState({})
  const paramNames = paramList.map(li => li.name)
  initialValues = { type: 'accept_datetime', cause_use_type: '包含', casetype: '全部', ...initialValues }
  if (params.length === 0) {
    params = paramList.filter(li => disableParams.indexOf(li.name) === -1)
  } else {
    const r = []
    params.forEach(n => {
      const index = paramNames.indexOf(n)
      if (index !== -1) {
        r.push(paramList[index])
      }
    })
    params = r
  }
  params = [...params, ...extendParams]
  useEffect(() => {
    initDictionary(setDictionary)
    initCaseTypeList(setCaseTypeList)
  }, [setDictionary, setCaseTypeList])
  useImperativeHandle(ref, () => ({
    showAll: () => setVisible(true),
    setFieldsValue: d => formRef.current.setFieldsValue(d),
    resetFields: () => formRef.current.resetFields(),
    submit: () => formRef.current.submit()
  }))
  return (
    <div className={style['search-container']}>
      <div className={style['search-form']}>
        <Form ref={formRef} name={name} initialValues={initialValues} {...layout} onFinish={d => getCondition(d, extendCondition, onChange)}>
          <Row gutter={24}>
            {params.map((li, i) => {
              const Param = li.component
              if (!li.defaultVisible && !visible) {
                return null
              }
              return (
                <Col key={i} span={8}>
                  <Param dictionary={dictionary} caseTypeList={caseTypeList} />
                </Col>
              )
            })}
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Item>
                <div className={style['search-btns']}>
                  <Button type='primary' ghost htmlType='submit'>搜索</Button>
                  <Button htmlType='reset' onClick={() => resetHandle(formRef)}>重置</Button>
                  <ToggleBtn value={visible} onChange={v => setVisible(v)} />
                </div>
              </Item>
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  )
}

const RefMain = forwardRef(Main)

RefMain.propTypes = {
  disableParams: PropTypes.array,
  params: PropTypes.array,
  name: PropTypes.string,
  onChange: PropTypes.func,
  initialValues: PropTypes.object,
  extendParams: PropTypes.array,
  extendCondition: PropTypes.func
}

RefMain.defaultProps = {
  disableParams: [],
  params: [],
  name: '',
  onChange: (condition, formData) => {},
  initialValues: {},
  extendParams: [],
  extendCondition: (condition, formData) => ({ condition, formData })
}

export default RefMain
